const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');
const PASSWORD_DEEP = 10;

let objectId =  Schema.Types.ObjectId;

//创建用户schema
const userSchema = new Schema({
    UserId:objectId,
    userName:{unique:true,type:String},
    password:String,
    sex:String,
    tag:String,
    creatAt:{type:Date,default:Date.now()},
    lastLoging:{type:Date,default:Date.now()}
});

//给密码加密
userSchema.pre('save',function(next){
    bcrypt.genSalt(PASSWORD_DEEP,(err,salt)=>{
        if(err)  return next(err);
        bcrypt.hash(this.password,salt,(err,has)=>{
           if(err) return next(err);
           this.password = has;
           next();
        })
    })
})


userSchema.methods = {
    //密码比对的方法
    comparePassword:(_password,password)=>{
        return new Promise((resolve,reject)=>{
            bcrypt.compare(_password,password,(err,isMatch)=>{
                if(!err) resolve(isMatch)
                else reject(err)
            })
        })
    }
}


mongoose.model('User',userSchema);